package com.app.manage.moudles.server.service.impl;

import cn.hutool.core.collection.CollectionUtil;

import cn.hutool.extra.ssh.JschUtil;
import com.app.manage.moudles.app.dao.TAppServerDao;
import com.app.manage.moudles.app.entity.TApp;
import com.app.manage.moudles.app.entity.TAppServer;
import com.app.manage.moudles.server.constant.ServerStatusEnums;
import com.app.manage.moudles.server.po.ServerNodePo;
import com.app.manage.utils.SFTPUtil;
import com.app.manage.utils.SftpFile;
import com.app.manage.utils.SshUtils;
import com.app.manage.utils.ThreadPoolUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.app.manage.moudles.server.dao.TServerDao;
import com.app.manage.moudles.server.entity.TServer;
import com.app.manage.moudles.server.service.TServerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务器-目前仅支持账号/密码登录(TServer)表服务实现类
 *
 * @author makejava
 * @since 2025-05-16 11:16:20
 */
@Service("tServerService")
@Slf4j
public class TServerServiceImpl extends ServiceImpl<TServerDao, TServer> implements TServerService {

    @Resource
    private TAppServerDao tAppServerDao;

    private ThreadPoolUtil threadPoolUtil = new ThreadPoolUtil();


    @Override
    public Page<TServer> pageData(Integer pageNum, Integer pageSize, TServer tServer) {
        //查询服务器信息
        LambdaQueryWrapper<TServer> query = new LambdaQueryWrapper<>();
        query.like(StringUtils.isNoneEmpty(tServer.getServerName()),TServer::getServerName,tServer.getServerName());
        query.like(StringUtils.isNoneEmpty(tServer.getServerIp()),TServer::getServerIp,tServer.getServerIp());
        if(StringUtils.isNotEmpty(tServer.getStatusList())){
            query.in(TServer::getServerStatus,tServer.getStatusList().split(","));
        }
        query.orderByDesc(TServer::getUpdateTime);
        Page<TServer> pageData = page(Page.of(pageNum,pageSize),query);
        if(CollectionUtil.isEmpty(pageData.getRecords())){
            return pageData;
        }
        //查询示例
        List<Integer>  serverIdList = pageData.getRecords().stream().map(TServer::getId).collect(Collectors.toList());
        List<TAppServer> appServerList = tAppServerDao.selectList(
                new LambdaQueryWrapper<TAppServer>().in(TAppServer::getServerId,serverIdList)
        );
        Map<Integer, Long> ipCountMap = appServerList.stream()
                .collect(Collectors.groupingBy(
                        TAppServer::getServerId,   // 根据年龄进行分组
                        Collectors.counting() // 统计每个年龄的数量
        ));
        pageData.getRecords().forEach(o->{
            o.setLoginUser("**");
            o.setLoginPwd("**");
            o.setStatusName(ServerStatusEnums.getNameByStatus(o.getServerStatus()));
            if(ipCountMap.get(o.getId()) != null){
                o.setAppServerCounts(ipCountMap.get(o.getId()));
            }
        });
        return pageData;
    }

    @Override
    public String saveData(TServer tServer) {
        long count = count(new LambdaQueryWrapper<TServer>()
                .ne(tServer.getId() != null,TServer::getId,tServer.getId())
                 .eq(TServer::getServerIp,tServer.getServerIp())
                .last(" limit 1"));
        if(count > 0){
            return "当前Ip已经配置！";
        }

        if(tServer.getId() == null){
            tServer.setCreateTime(new Date());
            tServer.setUpdateTime(new Date());
            save(tServer);
        }else {
            tServer.setUpdateTime(new Date());
            updateById(tServer);
        }
        return null;
    }

    @Override
    public String checkSshConnect(TServer t) {
        try {
            JschUtil.openSession(t.getServerIp(),t.getLoginPort(),t.getLoginUser(),t.getLoginPwd(),1000*5);

        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }
        return null;
    }

    @Override
    public <T> String removeIds(List<T> idList) {
        Integer appCounts = tAppServerDao.countAppForServer(idList);
        if(appCounts > 0){
            return "删除失败，部分服务器下存在运行的应用！";
        }
        remove(new LambdaQueryWrapper<TServer>().in(TServer::getId, idList));
        return null;
    }

    @Override
    public Integer checkAndUpdStatus() {
        //查询所有服务器
        List<TServer> serverList = list();
        if(CollectionUtils.isEmpty(serverList)){
            return 0;
        }
        for(TServer t : serverList){
            threadPoolUtil.submit(()->{
              Boolean isSuccess = SshUtils.checkSshConnect(t.getServerIp(),t.getLoginPort(),t.getLoginUser(),t.getLoginPwd(),10);
              Integer active = isSuccess?1:0;
              if(t.getServerStatus() - active != 0){
                  t.setServerStatus(active);
                  updateById(t);
              }

            });
        }
        return null;
    }

    @Override
    public List<ServerNodePo> listNodePo(Integer serverId,String prePath,String allPath) {

        log.info("入参：{} , {}",prePath,allPath);
        TServer server = getById(serverId);
        List<SftpFile> sftpFileList = SFTPUtil.lsNowFiles(
                server.getServerIp(),server.getLoginPort(),server.getLoginUser(),server.getLoginPwd()
                ,allPath
        );

        List<ServerNodePo> poList = new ArrayList<>();
        for(SftpFile s : sftpFileList){
            ServerNodePo po = new ServerNodePo();
            po.setId(s.getNowFile());
            po.setPid(prePath);
            po.setName(s.getNowFile());
            po.setIsParent(s.getFileType());
            po.setAllPath(s.getAllPath());
            poList.add(po);
        }

        return poList;
    }
}

